// 文章目录接口
const db = require("../db/index")

// 获取文章分类列表目录
exports.getCates = (req, res) => {
    const sql = "SELECT * FROM article_categories WHERE is_delete = 0 order by id asc"
    db.query(sql, (err, ret) => {
        if (err)
            res.cc(err)
        res.send({
            status: 0,
            msg: "获取文章分类列表成功",
            data: ret
        })
    })
}

// 增加文章分类
exports.addCate = (req, res) => {
    // 1.查询判断名称或者别名是否被占用
    const selectSql = "SELECT * FROM article_categories WHERE name = ? or alias = ?"
    db.query(selectSql, [req.body.name, req.body.alias], (err, ret) => {
        if (err)
            return res.cc(err)
        if (ret.length === 1) {
            if (ret[0].name === req.body.name && ret[0].alias === req.body.alias)
                return res.cc("文章名称,文章别名均以被占用")
            if (ret[0].alias === req.body.alias)
                return res.cc("文章别名被占用")
            return res.cc("文章名称已被占用")

        }
        if (ret.length === 2)
            return res.cc("文章名称,文章别名均以被占用")
        // 名称和别名均未冲突, 实现新增文章分类
        if (ret.length === 0) {
            const sql = "INSERT INTO article_categories SET ?"
            db.query(sql, req.body, (err, ret) => {
                if (err)
                    res.cc(err)
                if (ret.affectedRows !== 1) return res.cc("添加文章分类失败")
                res.cc("添加文章分类成功", 200)
            })
        }
    })
}

// 通过id删除目录
exports.deleteCate = (req, res) => {
    const sql = "UPDATE article_categories SET is_delete = 1 WHERE id = ?"
    db.query(sql, req.params.cateId, (err, ret) => {
        if (err)
            return res.cc(err)
        console.log(ret)
        if (ret.affectedRows !== 1)
            return res.cc("删除文章失败")
        res.cc("删除文章成功", 200)
    })
}

// 通过id更新目录信息
exports.updateCateById = (req, res) => {
    // 1.验证name和alias是否被使用
    const selectSql = "SELECT * FROM article_categories WHERE id != ? and (name = ? or alias = ?)"
    db.query(selectSql, [req.body.cateId, req.body.name, req.body.alias], (err, ret) => {
        if (err)
            return res.cc(err)
        if (ret.length === 1) {
            if (ret[0].name === req.body.name && ret[0].alias === req.body.alias)
                return res.cc("文章名称,文章别名均以被占用")
            if (ret[0].alias === req.body.alias)
                return res.cc("文章别名被占用")
            return res.cc("文章名称已被占用")
        }
        if (ret.length === 2)
            return res.cc("文章名称,文章别名均以被占用")
        if (ret.length === 0) {
            const sql = "UPDATE article_categories SET ? WHERE id = ?"
            db.query(sql, [{
                name: req.body.name,
                alias: req.body.alias
            }, req.body.cateId], (err, ret) => {
                if (err)
                    return res.cc(err)
                if (ret.affectedRows !== 1)
                    return res.cc("更新文章分类失败")
                res.cc("更新文章分类成功", 200)
            })
        }
    })
}